var superagent = require('superagent');
var CONFIG = require('../../../common/config');
var API_SERVER_URL = CONFIG.API_SERVER_FULL_URL;
/**
 * 请求工具类
 *
 * @author 王俊
 * @date 2018-07-02
 *
 * @param {String} url  请求地址
 * @param {Object} [options] 请求配置
 * @param {String} options.method 请求方法, GET/POST
 * @param {Object} options.body 请求体参数,
 * @param {Function} callback 回调函数
 */
module.exports = function (url, options, callback) {
    url = API_SERVER_URL + url;
    if (typeof options === 'function') {
        callback = options;
        options = {
            method : 'POST'
        }
    }
    options = options || {method : 'POST'};
    callback = callback || function (error, data) {
        console.log('request data default callback');
        if (error) console.log(error);
        if (data) console.log(data);
    };


    var method = options.method;
    var body = options.body;
    var r = superagent;
    r = method.toUpperCase() === 'GET' ? superagent.get(url) : superagent.post(url);
    r = body ? r.send(body) : r;
    r.end(function (error, response) {
        if(error) {
            return callback(error, null);
        }

        var retData = null;
        var errMsg = null;
        try {
            retData = JSON.parse(response.text);
            if(retData.success === 1) {
                retData = retData.data;
            } else {
                errMsg = retData.msg;
            }
        } catch (e) {
            errMsg = '请求失败';
        } finally {
            callback(errMsg, retData);
        }
    });
};